const fs = require("fs");
const path = require("path");
const archiver = require("archiver");
const { NodeSSH } = require("node-ssh");
const ssh = new NodeSSH();
const runCommand = require('./deploy/handleCommand')
ssh
  .connect({
    host: "112.74.82.5",
    username: "root",
    password:'pgh@Dream.com'
    // privateKeyPath: "/home/steel/.ssh/id_rsa",
  })
  .then(function () {
    // Local, Remote
    console.log("连接成功")
    //上传
    ssh
      .putFile(`${__dirname}/../dist.zip`,
        "/root/dist.zip"
      )
      .then(
        async function () {
          console.log("The File thing is done");
              // 执行解压命令
              await runCommand(ssh,'unzip dist.zip','/root')
              // 重命名
              await runCommand(ssh,'mv dist admin','/root')
              process.exit()
        },
        function (error) {
          console.log("Something's wrong");
          console.log(error);
        }
      );
  });

// 压缩文件
function compressFile() {
  // 正确设置本地dist文件路径
  const distPath = path.resolve(__dirname, "../dist");

  //创建文件输出流
  const output = fs.createWriteStream(`${__dirname}/../dist.zip`);
  const archive = archiver("zip", {
    zlib: { level: 3 }, // 压缩层级 目前我们只有2层
  }).on("error", (err) => {
    throw err;
  });

  // 文件输出流结束
  output.on("close", function () {
    console.log(archive.pointer() + " total bytes");
    console.log(
      "archiver has been finalized and the output file descriptor has closed."
    );
  });

  // 数据源是否耗尽
  output.on("end", function () {
    console.log("Data has been drained");
  });

  // 存档警告
  archive.on("warning", function (err) {
    if (err.code === "ENOENT") {
      console.warn("stat故障和其他非阻塞错误");
    } else {
      throw err;
    }
  });

  // 存档出错
  archive.on("error", function (err) {
    throw err;
  });

  //通过管道将归档数据传输到文件
  archive.pipe(output);
  // 压缩目录和名称
  archive.directory(distPath, "/dist");
  // 完成归档
  archive.finalize();
}
// 开始压缩
compressFile()
